package handler

import (
	"context"
	"errors"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"gorm.io/gorm"
	"hertz/demo/biz/model"
	"hertz/demo/biz/mw"
	"hertz/demo/biz/util"
	"net/http"
)

func AddJob(ctx context.Context, c *app.RequestContext) {
	var value model.Job
	if err := c.BindAndValidate(&value); err != nil {
		util.BadRequest(c, err)
		return
	}

	if err := model.AddJob(mw.GetDB(c), &value); err != nil {
		hlog.CtxErrorf(ctx, "AddJob db error: %w", err)
		util.ErrMessage(c, http.StatusInternalServerError, "db error")
		return
	}
	c.JSON(http.StatusOK, utils.H{"id": value.ID})
}

func ListSampleJob(ctx context.Context, c *app.RequestContext) {
	id, err := util.GetParamUint(c, "id")
	if err != nil {
		util.BadRequest(c, err)
		return
	}

	db := mw.GetDB(c)
	ret, err := model.ListSampleJob(db, uint(id))
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.NotFound()
		} else {
			hlog.CtxErrorf(ctx, "ListSampleJob db error: %w", err)
			util.ErrMessage(c, http.StatusInternalServerError, "db error")
		}
		return
	}

	c.JSON(http.StatusOK, ret)
}

func ListSelectionJob(ctx context.Context, c *app.RequestContext) {
	id, err := util.GetParamUint(c, "id")
	if err != nil {
		util.BadRequest(c, err)
		return
	}

	db := mw.GetDB(c)
	ret, err := model.ListSelectionJob(db, uint(id))
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.NotFound()
		} else {
			hlog.CtxErrorf(ctx, "ListSelectionJob db error: %w", err)
			util.ErrMessage(c, http.StatusInternalServerError, "db error")
		}
		return
	}

	c.JSON(http.StatusOK, ret)
}
